from rest_framework import serializers
from django.contrib.auth import authenticate
from django.contrib.auth.password_validation import validate_password
from rest_framework.authtoken.models import Token
# from rest_framework_simplejwt.tokens import RefreshToken, AccessToken
from .models import User, JobPosting, JobApplication, VideoQuestion, InterviewTemplate, InterviewSession, VideoAnswer, InterviewReport, VoiceProfile, SynthesizedAudio
from exams.models import LogistQuestion, ChoiceOption


class RegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(
        write_only=True,
        required=True,
        style={'input_type': 'password'}
    )

    class Meta:
        model = User
        fields = ['email', 'name', 'role', 'company', 'password']

    def create(self, validated_data):
        user = User.objects.create_user(
            email=validated_data['email'],
            name=validated_data['name'],
            role=validated_data['role'],
            password=validated_data['password'],
            company=validated_data.get('company', '')
        )
        return user


class LoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    email = serializers.EmailField(write_only=True)
    password = serializers.CharField(write_only=True, style={'input_type': 'password'})

    def validate(self, data):
        email = data.get('email')
        password = data.get('password')

        if not email or not password:
            raise serializers.ValidationError('必须同时提供"电子邮件"和"密码"。', code='authorization')

        user = authenticate(request=self.context.get('request'), email=email, password=password)
        if not user:
            raise serializers.ValidationError('无法使用提供的凭据登录。', code='authorization')
        
        # 使用 Django 内置的 Token 认证作为备用方案
        token, created = Token.objects.get_or_create(user=user)
        
        return {
            'user': user,
            'token': token.key,
        }


class UserSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    is_hr = serializers.BooleanField(read_only=True)
    is_candidate = serializers.BooleanField(read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'email', 'name', 'role', 'phone', 'avatar', 'company', 'is_hr', 'is_candidate']
        read_only_fields = ['id', 'is_hr', 'is_candidate']


class UserRegistrationSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    
    password = serializers.CharField(
        write_only=True,
        validators=[validate_password],
        style={'input_type': 'password'}
    )
    password_confirm = serializers.CharField(
        write_only=True,
        style={'input_type': 'password'}
    )
    
    class Meta:
        model = User
        fields = ['name', 'email', 'password', 'password_confirm', 'role', 'phone']
        extra_kwargs = {
            'password': {'write_only': True},
        }
    
    def validate(self, attrs):
        if attrs['password'] != attrs['password_confirm']:
            raise serializers.ValidationError("密码确认不匹配")
        return attrs
    
    def create(self, validated_data):
        validated_data.pop('password_confirm', None)
        user = User.objects.create_user(**validated_data)
        return user


class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    
    email = serializers.EmailField()
    password = serializers.CharField(style={'input_type': 'password'})
    role = serializers.ChoiceField(choices=User.ROLE_CHOICES)
    
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        role = attrs.get('role')
        
        if email and password:
            user = authenticate(email=email, password=password)
            
            if user:
                if not user.is_active:
                    raise serializers.ValidationError('用户账号已被禁用')
                
                if user.role != role:
                    raise serializers.ValidationError('用户角色不匹配')
                
                attrs['user'] = user
                return attrs
            else:
                raise serializers.ValidationError('邮箱或密码错误')
        else:
            raise serializers.ValidationError('必须提供邮箱和密码')


class TokenResponseSerializer(serializers.Serializer):
    """登录成功后返回的Token和用户信息"""
    token = serializers.CharField()
    user = UserSerializer() 


class VideoQuestionSerializer(serializers.ModelSerializer):
    """视频简答题序列化器"""
    created_by_name = serializers.CharField(source='created_by.name', read_only=True)
    category_display = serializers.CharField(source='get_category_display', read_only=True)

    class Meta:
        model = VideoQuestion
        fields = [
            'id', 'title', 'content', 'topic_tags', 
            'excellent_answer_example', 'scoring_criteria', 'answer_duration',
            'category', 'category_display', 'applicable_positions',
            'created_at', 'created_by', 'created_by_name'
        ]
        read_only_fields = ['id', 'created_at', 'created_by_name', 'category_display']

    def create(self, validated_data):
        # 自动将当前用户设置为创建者
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class JobPostingSerializer(serializers.ModelSerializer):
    """职位发布序列化器"""
    created_by_name = serializers.CharField(source='created_by.name', read_only=True)
    employment_type_display = serializers.CharField(source='get_employment_type_display', read_only=True)
    # 使用 a simplified template serializer 来显示关联的模板信息
    interview_template = serializers.SerializerMethodField()

    class Meta:
        model = JobPosting
        fields = [
            'id', 'title', 'department', 'location', 'employment_type', 'employment_type_display',
            'education', 'working_experience', 'requirements_skills', 'soft_skills',
            'description', 'number_of_hires', 'salary_range', 'benefits', 'contact_email',
            'application_deadline', 'is_active', 'required_match_score',
            'created_at', 'updated_at', 'created_by', 'created_by_name', 'interview_template'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by_name', 'interview_template', 'employment_type_display']

    def get_interview_template(self, obj):
        # 避免循环导入
        from .serializers import InterviewTemplateSimpleSerializer
        if hasattr(obj, 'interview_template'):
            return InterviewTemplateSimpleSerializer(obj.interview_template).data
        return None

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class InterviewTemplateSimpleSerializer(serializers.ModelSerializer):
    """简化的面试模板序列化器，用于嵌套显示"""
    class Meta:
        model = InterviewTemplate
        fields = ['id', 'title']


class InterviewTemplateSerializer(serializers.ModelSerializer):
    """面试模板序列化器"""
    created_by_name = serializers.CharField(source='created_by.name', read_only=True)
    # 在读取时，我们希望看到题目的详细内容
    logist_questions = serializers.SerializerMethodField()
    video_questions = VideoQuestionSerializer(many=True, read_only=True)
    
    # 在写入（创建/更新）时，我们只需要题目的ID列表
    logist_question_ids = serializers.ListField(
        child=serializers.IntegerField(), write_only=True, required=False
    )
    video_question_ids = serializers.ListField(
        child=serializers.IntegerField(), write_only=True, required=False
    )
    
    # 职位详细信息
    job_posting_title = serializers.CharField(source='job_posting.title', read_only=True)
    job_posting_department = serializers.CharField(source='job_posting.department', read_only=True)
    job_posting_location = serializers.CharField(source='job_posting.location', read_only=True)
    job_posting_employment_type = serializers.CharField(source='job_posting.employment_type', read_only=True)
    job_posting_employment_type_display = serializers.CharField(source='job_posting.get_employment_type_display', read_only=True)
    job_posting_education = serializers.CharField(source='job_posting.education', read_only=True)
    job_posting_working_experience = serializers.CharField(source='job_posting.working_experience', read_only=True)
    job_posting_requirements_skills = serializers.CharField(source='job_posting.requirements_skills', read_only=True)
    job_posting_soft_skills = serializers.CharField(source='job_posting.soft_skills', read_only=True)
    job_posting_description = serializers.CharField(source='job_posting.description', read_only=True)
    job_posting_number_of_hires = serializers.IntegerField(source='job_posting.number_of_hires', read_only=True)
    job_posting_salary_range = serializers.CharField(source='job_posting.salary_range', read_only=True)
    job_posting_benefits = serializers.CharField(source='job_posting.benefits', read_only=True)
    job_posting_contact_email = serializers.CharField(source='job_posting.contact_email', read_only=True)
    job_posting_application_deadline = serializers.DateTimeField(source='job_posting.application_deadline', read_only=True)
    job_posting_is_active = serializers.BooleanField(source='job_posting.is_active', read_only=True)
    job_posting_required_match_score = serializers.FloatField(source='job_posting.required_match_score', read_only=True)

    class Meta:
        model = InterviewTemplate
        fields = [
            'id', 'title', 'description', 'job_posting', 
            'job_posting_title', 'job_posting_department', 'job_posting_location',
            'job_posting_employment_type', 'job_posting_employment_type_display',
            'job_posting_education', 'job_posting_working_experience',
            'job_posting_requirements_skills', 'job_posting_soft_skills',
            'job_posting_description', 'job_posting_number_of_hires',
            'job_posting_salary_range', 'job_posting_benefits',
            'job_posting_contact_email', 'job_posting_application_deadline',
            'job_posting_is_active', 'job_posting_required_match_score',
            'created_by', 'created_by_name',
            'logist_questions', 'video_questions',
            'logist_question_ids', 'video_question_ids'
        ]
        read_only_fields = [
            'id', 'created_by_name', 'logist_questions', 'video_questions',
            'job_posting_title', 'job_posting_department', 'job_posting_location',
            'job_posting_employment_type', 'job_posting_employment_type_display',
            'job_posting_education', 'job_posting_working_experience',
            'job_posting_requirements_skills', 'job_posting_soft_skills',
            'job_posting_description', 'job_posting_number_of_hires',
            'job_posting_salary_range', 'job_posting_benefits',
            'job_posting_contact_email', 'job_posting_application_deadline',
            'job_posting_is_active', 'job_posting_required_match_score'
        ]

    def get_logist_questions(self, obj):
        # 动态导入以避免循环依赖
        from exams.serializers import LogistQuestionSerializer
        return LogistQuestionSerializer(obj.logist_questions.all(), many=True).data

    def create(self, validated_data):
        logist_ids = validated_data.pop('logist_question_ids', [])
        video_ids = validated_data.pop('video_question_ids', [])
        
        validated_data['created_by'] = self.context['request'].user
        template = InterviewTemplate.objects.create(**validated_data)
        
        if logist_ids:
            template.logist_questions.set(logist_ids)
        if video_ids:
            template.video_questions.set(video_ids)
            
        return template

    def update(self, instance, validated_data):
        logist_ids = validated_data.pop('logist_question_ids', None)
        video_ids = validated_data.pop('video_question_ids', None)

        instance = super().update(instance, validated_data)

        if logist_ids is not None:
            instance.logist_questions.set(logist_ids)
        if video_ids is not None:
            instance.video_questions.set(video_ids)
            
        return instance


class JobApplicationSerializer(serializers.ModelSerializer):
    """职位申请序列化器"""
    candidate_name = serializers.CharField(source='candidate.name', read_only=True)
    candidate_email = serializers.CharField(source='candidate.email', read_only=True)
    candidate_phone = serializers.CharField(source='candidate.phone', read_only=True)
    job_title = serializers.CharField(source='job_posting.title', read_only=True)
    company = serializers.CharField(source='job_posting.created_by.company', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    interview_recommendation_display = serializers.CharField(source='get_interview_recommendation_display', read_only=True)
    
    class Meta:
        model = JobApplication
        fields = [
            'id', 'candidate', 'candidate_name', 'candidate_email', 'candidate_phone',
            'job_posting', 'job_title', 'company',
            'resume_file', 'job_fit_score', 'core_skills_matched', 'soft_skills_detected',
            'education_summary', 'experience_summary', 'highlights',
            'interview_recommendation', 'interview_recommendation_display',
            'screening_feedback', 'screening_suggestions',
            'status', 'status_display', 'applied_at', 'self_introduction_video'
        ]
        read_only_fields = [
            'id', 'candidate', 'candidate_name', 'candidate_email', 'candidate_phone',
            'job_title', 'company', 'status_display',
            'interview_recommendation_display', 'applied_at'
        ]


class VoiceProfileSerializer(serializers.ModelSerializer):
    """语音配置序列化器"""
    voice_type_display = serializers.CharField(source='get_voice_type_display', read_only=True)
    
    class Meta:
        model = VoiceProfile
        fields = [
            'id', 'name', 'voice_type', 'voice_type_display', 'description', 
            'sample_audio_url', 'is_active', 'xunfei_vcn', 'speed', 'pitch', 
            'volume', 'created_at'
        ]
        read_only_fields = ['id', 'created_at', 'voice_type_display']


class SynthesizedAudioSerializer(serializers.ModelSerializer):
    """合成音频序列化器"""
    question_title = serializers.CharField(source='question.title', read_only=True)
    voice_profile_name = serializers.CharField(source='voice_profile.name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = SynthesizedAudio
        fields = [
            'id', 'question', 'question_title', 'voice_profile', 'voice_profile_name',
            'audio_file', 'text_content', 'duration', 'file_size', 'status', 
            'status_display', 'error_message', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'question_title', 'voice_profile_name', 'status_display', 
            'created_at', 'updated_at'
        ] 